package by.yakusekmaxim.bookgid.dataaccess.impl;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;

import org.hibernate.jpa.criteria.OrderImpl;
import org.springframework.stereotype.Repository;

import by.yakusekmaxim.bookgid.dataaccess.ImageDao;
import by.yakusekmaxim.bookgid.datamodel.Image;

@Repository
public class ImageDaoImpl extends AbstractDaoImpl<Long, Image> implements ImageDao {

    protected ImageDaoImpl() {
        super(Image.class);
    }
    
    @Override
    public List<Image> getAllImages(SingularAttribute<Image, ?> attr, boolean ascending, int startRecord, int pageSize) {
        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaQuery<Image> criteria = cBuilder.createQuery(Image.class);
        Root<Image> root = criteria.from(Image.class);

        criteria.select(root);
        criteria.orderBy(new OrderImpl(root.get(attr), ascending));

        TypedQuery<Image> query = getEm().createQuery(criteria);
        query.setFirstResult(startRecord);
        query.setMaxResults(pageSize);

        List<Image> results = query.getResultList();
        return results;
    }

	@Override
	public Long getCount() {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<Long> criteria = cBuilder.createQuery(Long.class);
		Root<Image> root = criteria.from(Image.class);

		criteria.select(cBuilder.count(root));

		TypedQuery<Long> query = getEm().createQuery(criteria);
		return query.getSingleResult();
	}
}
